package org.piggy.client.autoconfigure;

import org.apache.dubbo.config.spring.ServiceBean;
import org.piggy.client.support.dubbo.DubboClientRegisterManager;
import org.piggy.client.support.spring.SpringClientRegisterManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Servlet;

@Configuration
@EnableConfigurationProperties(ApiProperties.class)
@ConditionalOnProperty(prefix = "api", name = "enabled", havingValue = "true")
public class ApiClientAutoConfiguration {

    private ApiProperties apiProperties;

    @Autowired
    public void setApiProperties(ApiProperties apiProperties) {
        this.apiProperties = apiProperties;
    }

    @Bean
    @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
    @ConditionalOnMissingBean(SpringClientRegisterManager.class)
    public SpringClientRegisterManager springClientRegisterManager() {
        return new SpringClientRegisterManager(apiProperties);
    }

    @Bean
    @ConditionalOnClass({ServiceBean.class})
    @ConditionalOnMissingBean(DubboClientRegisterManager.class)
    public DubboClientRegisterManager dubboClientRegisterManager() {
        return new DubboClientRegisterManager(apiProperties);
    }
}
